<?php
namespace Admin\Controller;

class WechatEntController extends AdminController
{
    public $employee_db;
    public $dept_db;
    public $tag_db;
    public $enter_helper;
    public $token;

    public function __construct() {
        parent::__construct();

        $this->employee_db = D('Admin/Employee');
        $this->dept_db = M("Department",'tp_','DB_WX');
        $this->tag_db = M("Tag",'tp_','DB_WX');

        $this->token = 'ofanap1448334221';
        $this->enter_helper = new \ZL\Wechat\EnterpriseHelper($this->token);
    }

    public function test(){
        $data = D('Admin/Employee')->select();
        myDump($data);
    }
    public function index(){
        $position = D('Dict')->getDict('position',1);
        $this->assign('position',$position);
//        myDump($position);die;
        $this->display();
    }

    public function top(){

        $list = D('Admin/Employee')->select();
        $this->assign("list",$list);
        $this->display();
    }


    public function getDeptById()
    {
        $id = I('id');
//        $id = $this->_get('id','intval');
        $list = $this->dept_db->where(array('parentid' => $id))->select();
        if($list)
            $this->ajaxReturn($list);
        else {
            $data['status'] = 0;
            $this->ajaxReturn($data);
        }
    }

    //BUG department可以有多个部门，就会出问题
    public function getEmpByDeptId()
    {
//        $id = $this->_get('id','intval');
        $id = I('id');
        $list = D('Admin/Employee')->where(array('department' => array('like',"%$id%")))->select();
        $this->ajaxReturn($list);
    }

    public function syncTag(){
        $res = $this->enter_helper->getTags();
        if($res['errcode'] ==0 )
        {
            $taglist = $res['taglist'];
            foreach($taglist as $tag)
            {
                $taginfo = $this->tag_db->where(array('id' => $tag['tagid']))->find();

                //数据库里没有，则入库
                $data = array(
                    'id'         => $tag['tagid'],
                    'tagname'       => $tag['tagname'],
                );
                if(!$taginfo)
                {
                    $this->tag_db->add($data);
                }
                else
                {
                    $this->tag_db->where(array('id' => $tag['tagid']))->save($data);
                }
            }
        }
    }

    public function syncEmployee(){
        $res = $this->enter_helper->getMemebersDetailByDeptId(1,1);
//        myDump($res);die;
        if($res['errcode'] ==0 )
        {
            $userlist = $res['userlist'];
            foreach($userlist as $user)
            {
                myDump($user);
                echo '进去';
                D('Admin/Employee')->chckEmployee($user);
            }
        }
        else
            echo $res['errmsg'];
    }

    public function deleteNot(){
        $res = $this->enter_helper->getMemebersDetailByDeptId(1,1);
//        myDump($res);die;
        if($res['errcode'] ==0 )
        {
            $userlist = $res['userlist'];
            D('Admin/Employee')->chckHas($userlist);
        }
        else
            echo $res['errmsg'];
    }

    public function syncDept(){
        $res = $this->enter_helper->getDepartmentByID();
        if($res['errcode'] ==0 )
        {
            $deptlist = $res['department'];
//            myDump($deptlist);die;
            foreach($deptlist as $dept)
            {
                $deptinfo = $this->dept_db->where(array('id' => $dept['id']))->find();

                //数据库里没有，则入库
                $data = array(
                    'id'         => $dept['id'],
                    'name'       => $dept['name'],
                    'parentid'   => $dept['parentid'],
                    'sort'       => $dept['order'],
                );
                if(!$deptinfo)
                {
                    $this->dept_db->add($data);
                }
                else
                {
                    $this->dept_db->where(array('id' => $dept['id']))->save($data);
                }
            }
        }
    }

    public function addEmployee(){
//        $data = array(
//            "userid"        => "caizi",
//            "name"          => "菜籽",
//            "department"    => 4,
//            "position"      => "测试人员",
//            "mobile"        => "13735309690",
//            "gender"        => "2",
//            "email"         => "",
//            "weixinid"      => "selenefang",
//        );
        $data = I('post.');
        unset($data['remark']);
        $res = $this->enter_helper->createUser($data);
        $data = D('Admin/Employee')->getEmployee($data['userid']);
        $res = json_decode($res,true);
//        myDump($res);
        if($res['errcode']==0){
            $response['status'] = 1;
            $response['sign'] = '添加成功！';
        }else{
            $response['status'] = 0;
            $response['sign'] = $res['errmsg'];
        }
        $this->ajaxReturn($response);
    }

    public function getEmployee(){
        $userId = I('userid');
        D('Admin/Employee')->getEmployee($userId);
        $data = D('Admin/Employee')->where(['userid'=>$userId])->find();
        $data['errcode'] = 0 ;
        $this->ajaxReturn($data);
    }

    public function loading(){
        D('Admin/Employee')->loading();
    }

    public function updateEmployee()
    {
        $data = I('post.');
//        myDump($data);die;
        if($data['isadd']==1){
            unset($data['isadd']);
        }else{
            $empData = D('Admin/Employee')->where(array('userid'=>$data['userid']))->find();
            $depart = $data['department'];
            $data['department'] = explode(',',$empData['department']);
            $data['department'][] = $depart;
            unset($data['isadd']);
        }
//        myDump($data);
        $res = $this->enter_helper->updateUser($data);
        $data = D('Admin/Employee')->getEmployee($data['userid']);
//        myDump($res);die;
        $res = json_decode($res,true);
        if($res['errcode']==0){
            $response['status'] = 1;
            $response['sign'] = '修改成功！';
        }else{
            $response['status'] = 0;
            $response['sign'] = $res['errmsg'];
        }
        $this->ajaxReturn($response);
    }
    public function deleteEmployee()
    {
        $userid = I('userid');
        $res = $this->enter_helper->deleteUser($userid);
        $res = json_decode($res);
//        myDump($res);
        $res = object_array($res);
        if($res['errcode']==0){
            D('Admin/Employee')->where(array('userid'=>$userid))->delete();
            $response['status'] = 1;
            $response['sign'] = '删除成功！';
        }else{
            $response['status'] = 0;
            $response['sign'] = $res['errmsg'];
        }
        $this->ajaxReturn($response);
    }

    public function deptIndex(){
        $this->display();
    }

    public function getDept(){
        $id = I('id');
        $data = D('Depart')->find($id);
        $this->ajaxReturn($data);
    }
    public function updateDept(){
        if(D('Depart')->updateDept()){
            $data['status'] = 1;
        }else{
            $data['status'] = 0;
        }
        $this->ajaxReturn($data);
    }
    public function addDept(){
        if(D('Depart')->addDept()){
            $data['status'] = 1;
        }else{
            $data['status'] = 0;
        }
        $this->ajaxReturn($data);
    }
    public function delDept(){
        $id = I('id');
        $res = $this->enter_helper->deleteDept($id);
        $res = json_decode($res, true);
        if($res['errcode']!==0) {
            D('Depart')->where(array('id'=>$id))->delete();
            $this->success('删除成功');
        }else {
            $this->error('删除失败');
        }
    }

    public function onlineState(){
        $dep = D('Depart')->where(['parentid'=>14])->select();
        $this->assign('dep',$dep);
        $this->display();
    }

    public function getCommunityEmployee(){
        $depId = I('id');
        $depData = D('Depart')->find($depId);
        $dep_name = $depData['name'];
        $community_id = $depData['community_id'];
        $map['a.DEPT_NAME'] = array('like',"%$dep_name%");
        $map['a.assistant_map'] = array('like',"%$community_id%");
        $map['_logic'] = 'or';
        $where['b.role_id'] = 4;
        $where['a.is_active'] = 1;
        $where['_complex'] = $map;
        $assistant = M('User')->alias('a')->join('left join zh_role_user b on a.id=b.user_id')->where($where)->select();

        $employee = D('Employee')->where(['department'=>['like',"%$depId%"]])->select();
//        myDump($employee);
        D('Depart')->getDepName($employee,2);
        $res['employee'] = $employee;
        $res['assistant'] = $assistant;
        $this->ajaxReturn($res);
    }

    public function employeeState(){
        $data['id'] = I('id');
        $data['onLine'] = I('status');
        $ok = D('Employee')->data($data)->save();
        if($ok){
            $res['status'] = 1;
            $res['msg'] = '修改成功';
        }else{
            $res['status'] = false;
            $res['msg'] = '修改失败';
        }
        $this->ajaxReturn($res);
    }
    public function assistantState(){
        $data['id'] = I('id');
        $data['onLine'] = I('status');
        $ok = M('User')->data($data)->save();
        if($ok){
            $res['status'] = 1;
            $res['msg'] = '修改成功';
        }else{
            $res['status'] = false;
            $res['msg'] = '修改失败';
        }
        $this->ajaxReturn($res);
    }
}